export function handleTree(data, id, parentId, children, rootId) {
	id = id || 'id'
	parentId = parentId || 'parentId'
	children = children || 'children'
	rootId = rootId || 0
	//对源数据深度克隆
	const cloneData = JSON.parse(JSON.stringify(data))
	//循环所有项
	const treeData = cloneData.filter(father => {
		let branchArr = cloneData.filter(child => {
			//返回每一项的子级数组
			return father[id] === child[parentId]
		});
		branchArr.length > 0 ? father.children = branchArr : '';
		//返回第一层
		return father[parentId] === rootId;
	});
	return treeData != '' ? treeData : data;
}
/**处理金额*/
export function splitYuanToParts(yuan) {
  const [intPart, decimalPart = '00'] = Number(yuan).toFixed(2).split('.');
  return { intPart, decimalPart };
}

// 日期格式化
export function parseTime(time, pattern) {
	if (arguments.length === 0 || !time) {
		return null
	}
	const format = pattern || '{y}-{m}-{d} {h}:{i}:{s}'
	let date
	if (typeof time === 'object') {
		date = time
	} else {
		if ((typeof time === 'string') && (/^[0-9]+$/.test(time))) {
			time = parseInt(time)
		} else if (typeof time === 'string') {
			time = time.replace(new RegExp(/-/gm), '/');
		}
		if ((typeof time === 'number') && (time.toString().length === 10)) {
			time = time * 1000
		}
		date = new Date(time)
	}
	const formatObj = {
		y: date.getFullYear(),
		m: date.getMonth() + 1,
		d: date.getDate(),
		h: date.getHours(),
		i: date.getMinutes(),
		s: date.getSeconds(),
		a: date.getDay()
	}
	const time_str = format.replace(/{(y|m|d|h|i|s|a)+}/g, (result, key) => {
		let value = formatObj[key]
		// Note: getDay() returns 0 on Sunday
		if (key === 'a') {
			return ['日', '一', '二', '三', '四', '五', '六'][value]
		}
		if (result.length > 0 && value < 10) {
			value = '0' + value
		}
		return value || 0
	})
	return time_str
}

/**
 * 获取用户位置授权，并引导授权，返回结果
 */
export function pointAddresAuth() {
	var that = this;
	return new Promise(resolve => {
    //#ifdef H5
    resolve(true)
    //#endif

    //#ifndef H5
		uni.getSetting({
			success(res) {
				console.log(res)
        let authRes = res.authSetting["scope.userLocation"];
				if (authRes == undefined) {
          uni.authorize({
            scope: "scope.userLocation",
            success (res) {
                console.log('授权结果',res)
                uni.showToast({
                	title: '授权成功',
                	icon: 'success',
                	duration: 1500
                })
                resolve(true)
            },
            fail(res) {
              console.log('授权结果',res)
              uni.showToast({
              	title: '授权失败',
              	icon: 'none',
              	duration: 1500
              })
              resolve(false)
            },
            complete(res) {
               console.log('授权结果',res)
            }
          })

      }else if(!authRes){
					uni.showModal({
						title: '提示',
						content: '需要获取用户当前位置',
						showCancel: true,
						success(res) {
							console.log(res)
							if (res.confirm) {
								uni.openSetting({
									success(res) {
										console.log(res)
										if (res.authSetting["scope.userLocation"]) {
											uni.showToast({
												title: '授权成功',
												icon: 'success',
												duration: 1500
											})
											resolve(true)
										} else {
											uni.showToast({
												title: '授权失败',
												icon: 'none',
												duration: 1500
											})
											resolve(false)
										}
									}
								})
							} else {
								uni.showToast({
									title: '取消授权',
									icon: 'none',
									duration: 1500
								})
								resolve(false)
							}
						}
					})
				} else {
					resolve(true)
				}
			}
		})
    //#endif
	})
}

/**
 * 统计页数
 * @param {Number} total 总页数
 * @param {Number} pageSize 每页数量
 */
export function getPage(total, pageSize) {
	return total % pageSize == 0 ? parseInt(total / pageSize) : Math.ceil(total / pageSize)
}


/**
 * 前后不是同一人登录，清除缓存
 */
export function removeStorage(){
	uni.removeStorageSync('uid');
	uni.removeStorageSync('deviceAzData');
	uni.removeStorageSync('matterReformData');
	uni.removeStorageSync('deviceAzCheckData');
	uni.removeStorageSync('matterCheckData');
	uni.removeStorageSync('matterDeviceData');
	uni.removeStorageSync('dictData');
	uni.removeStorageSync('craftKpi');
	uni.removeStorageSync('initTreeselectProject');
	uni.removeStorageSync('initListQrCode');
	uni.removeStorageSync('jrsgData');
	uni.removeStorageSync('installCheckDeviceListData');
	uni.removeStorageSync('deviceMatterListData');
	uni.removeStorageSync('initMatterCheckListData');
	uni.removeStorageSync('installCheckDeviceListData');
	uni.removeStorageSync('initDeviceList');
	uni.removeStorageSync('initMatterList');
	uni.removeStorageSync('installDeviceListData');
	uni.removeStorageSync('deviceStorage');
}
